<?php

namespace app;

use think\exception\Handle;
use think\exception\HttpResponseException;
use Throwable;
use think\Response;
use think\exception\HttpException;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    public function render($request, Throwable $e): Response
    {
        // 调试模式
        if ($request->isAjax()) {
            if ($e instanceof HttpResponseException) {
                return $e->getResponse();
            } elseif ($e instanceof HttpException) {
                if (env('app_debug')) {
                    return json(['code' => $e->getStatusCode(), 'msg' => $e->getMessage()], $e->getStatusCode());
                }
            } else {
                if (env('app_debug')) {
                    return json(['code' => 500, 'msg' => $e->getMessage(), 'trace' => $e->getTrace()], 500);
                }
            }

            return json(['code' => 500, 'msg' => '服务器升级中，请稍后重试~~'], 500);
        }

        return parent::render($request, $e);
    }
}
